import React,{useState, useEffect} from 'react'
import { Upload, message } from 'antd';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import './loader.less'
function getBase64(img: any, callback: Function) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}

function beforeUpload(file: File) {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('You can only upload JPG/PNG file!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('Image must smaller than 2MB!');
  }
  return isJpgOrPng && isLt2M;
}

const LoaderContent = (props: any) => {
  const [loading, setloading] = useState<boolean>(false);
  const [imageUrl, setimageUrl] = useState<string>('');
  const handleChange = (info: any) => {
    if (info.file.status === 'uploading') {
      setloading(true)
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj, (imageUrl: string) =>{
        setloading(true)
        setimageUrl(imageUrl)
      }
      );
    }
  };
  useEffect(() => {
    setimageUrl(props.imageUrl)
  }, [props.imageUrl])
  const uploadButton = (
    <div className='uploadButton' style={{width: props.style.width || 150, height: props.style.height || 130}}>
      <div>
        {loading ? <LoadingOutlined /> : <PlusOutlined />}
        <div style={{ marginTop: 8 }}>{props.imgTitle || '上传图片'}</div>
      </div>
    </div>
  );  
  return (
    <div>
      <Upload
        name="avatar"
        disabled={props.disabled || false}
        listType="picture-card"
        className="avatar-uploader"
        showUploadList={false}
        action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
        beforeUpload={beforeUpload}
        onChange={handleChange}
      >
        {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: props.style.width || 150, height: props.style.height || 130 }} /> : uploadButton}
      </Upload>      
    </div>
  )
}

export default LoaderContent
